class Bookmarklet

  baseURL: '<%= ENV["FEEDBIN_URL"] %>'
  createPath: '<%= Rails.application.routes.url_helpers.pages_path %>'

  save: ->
    xhr = new XMLHttpRequest
    xhr.open 'POST', @url()
    xhr.setRequestHeader 'Content-Type', 'application/json'
    xhr.onload = =>
      @originalTitle()
      @currentScript().parentNode.removeChild(@currentScript())
    xhr.send @data()

  data: ->
    JSON.stringify
      page_token: @pageToken()
      url: window.location.href
      title: document.title

  url: (path) ->
    @baseURL + @createPath

  pageToken: ->
    @currentScript().getAttribute('data-feedbin-token')

  originalTitle: ->
    title = @currentScript().getAttribute('data-original-title')
    if title != null
      document.title = title

  currentScript: ->
    document.querySelector('script[data-feedbin-token]')

bookmarklet = new Bookmarklet
bookmarklet.save()